package org.springframework.boot.autoconfigure.mock.strategy;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mock.model.MockResMeta;
import org.springframework.boot.autoconfigure.mock.model.MockResTypeEnum;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

/**
 * @author: hooware
 * @Date: 2021/12/26 18:15
 * @Description:
 */
public class PropertyValueMockResProcessor implements IMockResProcessor, EnvironmentAware {

    @Autowired
    private Gson gson;

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public boolean match(MockResTypeEnum mockResTypeEnum) {
        return MockResTypeEnum.PROP.equals(mockResTypeEnum);
    }

    @Override
    public Object mockProcess(MockResMeta mockResMeta) {
        final String property = environment.getProperty(mockResMeta.getValue());
        // 1.从env配置中获取需要mock的响应数据
        if (StringUtils.isNotBlank(property)) {
            return gson.fromJson(property, mockResMeta.getReturnType());
        }
        // 2.不符合策略条件时默认返回null进行handler兜底
        return null;
    }
}
